// src/rabbitmqService.js
import Stomp from 'stompjs'
import SockJS from 'sockjs-client'

let stompClient = null

export const connectRabbitMQ = (onMessageReceived) => {
  const socket = new SockJS('http://localhost:15674/stomp') // 替换为你的 RabbitMQ WebSocket 地址
  stompClient = Stomp.over(socket)

  const headers = {
    login: 'guest', // RabbitMQ 用户名
    passcode: 'guest', // RabbitMQ 密码
  }

  stompClient.connect(
    headers,
    () => {
      console.log('Connected to RabbitMQ')

      // 订阅队列，设置接收消息的回调
      stompClient.subscribe('/queue/live/room', (message) => {
        console.log(message)
      })
    },
    (error) => {
      console.error('RabbitMQ connection error:', error)
    }
  )
}

export const sendMessageToQueue = (queueName, message) => {
  if (stompClient && stompClient.connected) {
    stompClient.send(`/queue/${queueName}`, {}, message)
    console.log(`Message sent to ${queueName}: ${message}`)
  } else {
    console.error('Not connected to RabbitMQ')
  }
}

export const disconnectRabbitMQ = () => {
  if (stompClient && stompClient.connected) {
    stompClient.disconnect(() => {
      console.log('Disconnected from RabbitMQ')
    })
  }
}
